package com.example.controllor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserControllor {

    @Resource
    UserService userService;

    @PostMapping("/add")
    public Result add(@RequestBody User user){ //@RequestBody: 表示将请求体中的json数据转换为User对象
        userService.add(user);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){ //@PathVariable: 表示从路径中获取参数
        userService.delete(id);
        return Result.success();
    }

    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<User> list){ //@RequestBody: 批量删除
        userService.deleteBatch(list);
        return Result.success();
    }
    @PutMapping("/update")
    public Result update(@RequestBody User user){ //@RequestBody: 表示将请求体中的json数据转换为User对象
        userService.update(user);
        return Result.success();
    }
    @GetMapping("/selectAll")  //  接口的路径
    public Result selectAll(User user){
        List<User> userList = userService.selectAll(user);
        return Result.success(userList);

    }

    /*
     *   分页查询
     * pageNum: 当前页码
     * pageSize: 每页的个数
     * */
    @GetMapping("/selectPage")// 接口的路径
    public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             // @RequestParam(required = false) String name
                             User user
    ) {

        PageInfo<User> pageInfo = userService.selectPage(pageNum, pageSize, user);
        return Result.success(pageInfo); //返回的是分页的对象
    }
    //  导出数据
    @GetMapping("/export")
    public void exportData(User user, HttpServletResponse response) throws Exception {
        String ids = user.getIds();
        if (StrUtil.isNotBlank(ids)) {
            String[] idsArr = ids.split(",");
            user.setIdsArr(idsArr);
        }
        // 查询所有数据
        List<User> list = userService.selectAll(user);
        // 创建ExcelWriter对象
         ExcelWriter writer = ExcelUtil.getWriter(true);
         // 设置表头别名
         writer.addHeaderAlias("username", "账号");
        writer.addHeaderAlias("name", "名称");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("email", "邮箱");
        // 设置只输出指定的列
        writer.setOnlyAlias(true);
        // 将数据写入到Excel中
        writer.write(list, true);
        // 设置输出的文件名称以及输出流的头信息
        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("管理员信息", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream os = response.getOutputStream();
        writer.flush(os);
        writer.close();
        os.close();

    }
//    批量导入数据
    @PostMapping("/import")
    public Result importData( MultipartFile file) throws Exception {
        // 获取Excel文件的输入流
        InputStream inputStream = file.getInputStream();
        //  创建ExcelReader对象
        ExcelReader reader =  ExcelUtil.getReader(inputStream);
        // 通过Reader对象读取Excel数据
        reader.addHeaderAlias( "账号","username"  );
        reader.addHeaderAlias( "名称","name"  );
        reader.addHeaderAlias( "电话","phone");
        reader.addHeaderAlias( "邮箱","email");
        List<User> list =  reader.readAll(User.class);

        for (User user : list) {
            userService.add(user);
        }
        return Result.success();
    }

}
